﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Data;
using System.Web.UI.WebControls;
using System.Text;

/// <summary>
/// 将数据导出成Excel文件的类
/// 数据列的顺序按照 Gridview中列的顺序
/// </summary>
namespace HZ.DrugTrade.Web
{
    public class ExportFile
    {
        /// <summary>
        /// 将DataSet导出成CSV格式
        /// </summary>
        /// <param name="ds">DataSet</param>
        /// <returns>CSV字符串数据</returns>
        private string ExportCSV(DataTable tb)//DataSet ds
        {
            StringBuilder data = new StringBuilder();

           data.Append("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\"><tr style=\"font-weight: bold; white-space: nowrap;\">"); //add by ysm 2013-01-30

            //写出列名
            foreach (DataColumn column in tb.Columns)
            {
                if (IsExport(column))
                    data.Append("<td>" + column.ExtendedProperties["FieldCHS"].ToString() + "</td>"); //add by ysm 2013-01-30
                    //data.Append( column.ExtendedProperties["FieldCHS"].ToString() + ",");   //column.ColumnName + ",";
            }
             data.Append("</tr>"); //add by ysm 2013-01-30
            // data.Append( "\n");

            //写出数据
            foreach (DataRow row in tb.Rows)
            {
                foreach (DataColumn column in tb.Columns)
                {
                    //判断列是否导出 
                    if (IsExport(column))
                      data.Append("<td style='vnd.ms-excel.numberformat:@'>" + row[column].ToString().Replace(",", "，").Replace((char)13, ' ').Replace((char)10, ' ') + "</td>"); //add by ysm 2013-01-30
                      // data.Append(row[column].ToString().Replace(",", "，").Replace((char)13, ' ').Replace((char)10, ' ') + ",");
                }
                data.Append("</tr>"); //add by ysm 2013-01-30
                //data.Append("\n");
            }
            data.Append("</table>"); //add by ysm 2013-01-30
            return data.ToString();
        }

        /// <summary>
        /// 标记DataColumn为接受导出的
        /// </summary>
        /// <param name="column">DataColumn</param>
        private void SetExport(DataColumn column, string headertext)
        {
            if (column != null)
            {
                //将列推到集合的最后，以便输出的时候按顺序输出
                column.SetOrdinal(column.Table.Columns.Count-1);

                if (column.ExtendedProperties["IsExport"] == null)
                    column.ExtendedProperties.Add("IsExport", "true");
                else
                    column.ExtendedProperties["IsExport"] = "true";
                //保存列的中文名
                if (column.ExtendedProperties["FieldCHS"] == null)
                    column.ExtendedProperties.Add("FieldCHS", headertext);
                else
                    column.ExtendedProperties["FieldCHS"] = headertext;
            }
        }

        /// <summary>
        /// 标记DataTable中的一些列为接受导出的
        /// </summary>
        /// <param name="tb">DataTable</param>
        /// <param name="columns">DataGrid的列</param>
        private void SetExport(DataTable tb, DataControlFieldCollection columns)//DataGridColumnCollection
        {
            foreach (DataControlField column in columns)//DataGridColumn
            {
                if (column.GetType().Name.ToLower() == "boundfield")
                {
                    SetExport(tb.Columns[(column as BoundField).DataField], (column as BoundField).HeaderText);//column.HeaderText
                }
            }
        }

        /// <summary>
        /// 判断DataColumn是否为接受导出的
        /// </summary>
        /// <param name="column">DataColumn</param>
        /// <returns>bool型的结果</returns>
        private bool IsExport(DataColumn column)
        {
            if (column.ExtendedProperties["IsExport"] != null && column.ExtendedProperties["IsExport"].ToString().Trim().ToLower() == "true")
                return true;
            else
                return false;
        }


        public void ExportData(DataTable dt, GridView gvwinfo, System.Web.UI.Page Page)
        {
            SetExport(dt, gvwinfo.Columns);

            string data =ExportCSV(dt); // Export.ExportCSV(ds);

            Page.Response.Clear();
            Page.Response.Buffer = true;
            Page.Response.Charset = "GB2312";
            string temp = string.Format("attachment;filename={0}", "ExportData.xls");
            Page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
            Page.Response.ClearHeaders();
            Page.Response.ContentType = "application/ms-excel";  //add by ysm 2013-01-30
            Page.Response.AppendHeader("Content-disposition", temp);
            Page.Response.Write(data);
            //HttpContext.Current.ApplicationInstance.CompleteRequest();
            Page.Response.End();
        }


        /// <summary>
        /// 
        /// </summary>
        public static ExportFile Instance
        {
            get { return new ExportFile(); }
        }
    }

}
